/*
 * redmicro all Copyright (c)
 * Created by seeker910 on 2015/7/2.
 * 
 * 主从表单
 */
Rsd.define('Rsd.widget.MajorSubForm', {
    extend: 'Rsd.container.Component',
    requires: [
        'Rsd.widget.ModelForm',
        'Rsd.control.Grid',
        'Rsd.control.SearchToolBar',
        'Rsd.form.ComboBoxEx',
        'Rsd.form.Timestamp'
    ],
    xtype:'major-sub-form',
    layout: 'vbox',
    items: [
        {
            xtype: 'model-form',
            margin:'5 15 5 15',
            header:{
                text:'主表信息',
                space:0,
                style:{
                    textAlign: 'center',
                    alignSelf:'end',
                    fontSize:'130%',
                    margin: '0 0 0 0px', 
                    width:100,
                    height: '30px',
                    'lineHeight': '30px',
                    border: '1px grey solid',
                    borderStartEndRadius: '5px',
                    borderStartStartRadius:'5px',
                    borderBottomWidth: '0px'
                }
            },
            toolBar:
            {
                xtype:'container',
                header:false,
                position:'top',
                height:45,
                layout:{
                    type:'hbox',
                    align:'right'
                },
                style:{display:'flex'},
                space:0,
                items:[
                    {
                        xtype:'svg',
                        dsTagName:'redjs.modify',
                        width:60,
                        hidden:true,
                        label:{content:'修 改',position:'right',space:2,width:35},
                        handlerTarget:'dom',
                        handler:'_modifyMajorHandler'
                    },
                    {
                        xtype:'svg',
                        dsTagName:'redjs.save',
                        width:60,
                        label:{content:'保 存',position:'right',space:2,width:35},
                        handlerTarget:'dom',
                        handler:'_saveMajorHandler'
                    },
                    {
                        xtype:'svg',
                        dsTagName:'redjs.cancel',
                        width:60,
                        label:{content:'取 消',position:'right',space:2,width:35},
                        handlerTarget:'dom',
                        handler:'_cancelMajorModifyHandler'
                    }
                ]
            },
            legend: false,
            fields:[],
            height: 'auto',
            bodyStyle:{ 
                backgroundColor: 'white',
                border: '1px rgb(129, 112, 86) solid ',  
                //borderEndEndRadius: '5px',
                //borderBottomLeftRadius: '5px',
                //borderTopRightRadius: '5px',
                borderTopLeftRadius: '5px'
            }
        },
        {
            xtype:'grid',
            readonly:false,
            margin: '15 15 15 15',
            toolBar:{
                xtype: 'search-tool-bar',
                height:'auto',
                width:'100%',
                space:0,
                style:{minHeight:50},
                header:{
                    //xtype:'label',  
                    text:'从表信息',
                    visible:true,
                    space:0,
                    position:'right',
                    style:{
                        margin: '22px 0px 0px 0px', 
                        textAlign: 'center',
                        alignSelf:'end',
                        fontSize:'130%',
                        width:100,
                        height: '30px',
                        'lineHeight': '30px',
                        border: '1px grey solid',
                        borderStartEndRadius: '5px',
                        borderStartStartRadius:'5px',
                        borderBottomWidth: '0px'
                    }
                },  
            }, 
            "columns": [],
            "fields": [],
            titleMember:null,
            flex: 1,
            style:{
                minHeight:200,
            },
            ctrlStyle:{ 
                backgroundColor: 'white',
                border: '1px rgb(129, 112, 86) solid ',
                //borderEndEndRadius: '5px',
                //borderBottomLeftRadius: '5px',
                //borderTopRightRadius: '5px',
                borderTopLeftRadius: '5px'
            }
        }
    ],
    opColumns: [
        {
            name: 'edit',
            text: '操 作',
            nobr: true, 
            width: 100,
            xtype: 'template', 
            format: 'rowOpFormat'
        }, {
            name: 'space',
            text: '',
            xtype: 'template',
            width: 5,
            hideable: false,
            sortable: false
        }
    ],
    /*
     * */
    constructor: function MajorSubForm(config) {

        config = config || {};
        this.apply(config); 
    },
    /**
     * 
     */
    _saveMajorHandler:function _saveMajorHandler(){ 
                           
        var me = this;   
        
        var callback = function(){
            //表单状态控制
            var editable = false;
            me.setMajorMode(editable)
             //按钮状态控制
             me.items[0].toolBar.content.items[0].show()
             me.items[0].toolBar.content.items[1].hide();
             me.items[0].toolBar.content.items[2].hide();
        };
       
        this.funApplyByIOC('saveMajor',[callback]);
       
    },
    /**
     * 
     */
    _modifyMajorHandler:function _modifyMajorHandler(){
        var me = this;       
        var callback = function()
        {
            //表单状态控制
            var editable = true;
            me.setMajorMode(editable)

            //按钮状态控制
            me.items[0].toolBar.content.items[0].hide();
            me.items[0].toolBar.content.items[1].show()
            me.items[0].toolBar.content.items[2].show();
        };
       
        this.funApplyByIOC('modifyMajor',[callback]);
    },
    /**
     * 
     */
    _cancelMajorModifyHandler:function _cancelMajorModifyHandler(){
        var me = this;          
        var callback = function(){
            //表单状态控制
            var editable = false;
            me.setMajorMode(editable); 
            //恢复数据
            me.loadMajor();
            //按钮状态控制
            me.items[0].toolBar.content.items[0].show()
            me.items[0].toolBar.content.items[1].hide();
            me.items[0].toolBar.content.items[2].hide();
        }; 
        
        this.funApplyByIOC('cancelMajorModify',[callback]);
    },
    /*
     * */
    rowOpFormat: function rowOpFormat(row,args) {

        if (this.items[1].readonly) {
            return [];
        }
        var me = this;
        var tr = args.tr;
        var editing = tr && tr.classList && tr.classList.contains('x-row-edit');
        //console.log(editing);

        var btnUpdate = document.createElement('a');
        btnUpdate.href = '#';
        btnUpdate.innerHTML = '修改';
        btnUpdate.style.display = editing?'none':'inline-table';
        btnUpdate.style.width='45px';
        btnUpdate.style.textAlign ="right";
        btnUpdate.style.margin ="0 5px 0 5px";
        btnUpdate.style.backgroundImage ='url('+Rsd.getRedjsHost() + "/resources/svg/update.svg"+')';
        btnUpdate.style.backgroundPosition ='left center';
        btnUpdate.style.backgroundSize = '12px';
        btnUpdate.style.backgroundRepeat = 'no-repeat' ;
 
        $(btnUpdate).click(function () {
            
            var tr = this.parentNode.parentNode.parentNode; 
            me.items[1].editTr(tr,true);
            //
            btnUpdate.style.display = 'none';
            btnDel.style.display = 'none';
            btnSave.style.display = 'inline-table';
            btnCancel.style.display = 'inline-table'; 
        });

        var btnDel = document.createElement('a');
        btnDel.href = '#';
        btnDel.innerHTML = '删除';
        btnDel.style.display = editing?'none':'inline-table';
        btnDel.style.width='45px';
        btnDel.style.textAlign ="right";
        btnDel.style.margin ="0 5px 0 5px";
        btnDel.style.backgroundImage ='url('+Rsd.getRedjsHost() + "/resources/svg/delete.svg"+')';
        btnDel.style.backgroundPosition ='left center';
        btnDel.style.backgroundSize = '12px';
        btnDel.style.backgroundRepeat = 'no-repeat' ;
        $(btnDel).click(function (sender,evt) {

            var tr = this.parentNode.parentNode.parentNode; 
            var callback = function()
            {
                me.items[1].deleteTr(tr);
            };
            me.funApplyByIOC('deleteSubItem',[row,evt,callback]);
           
            
        });

        var btnSave = document.createElement('a');
        btnSave.href = '#';
        btnSave.innerHTML = '保存';
        btnSave.style.display = editing?'inline-table':'none';
        btnSave.style.width='45px';
        btnSave.style.textAlign ="right";
        btnSave.style.margin ="0 5px 0 5px";
        btnSave.style.backgroundImage ='url('+Rsd.getRedjsHost() + "/resources/svg/save.svg"+')';
        btnSave.style.backgroundPosition ='left center';
        btnSave.style.backgroundSize = '12px';
        btnSave.style.backgroundRepeat = 'no-repeat' ;
        $(btnSave).click(function (sender,evt) {

            var tr = this.parentNode.parentNode.parentNode; 
            me.items[1].writeRow(tr);

            var callback = function()
            { 
                me.items[1].editTr(tr,false);
                //
                btnUpdate.style.display = 'inline-table';
                btnDel.style.display = 'inline-table';
                btnSave.style.display = 'none';
                btnCancel.style.display = 'none'; 
            }
            me.funApplyByIOC('saveSubItem',[row,evt,callback]);
            
            
        });

        var btnCancel = document.createElement('a');
        btnCancel.href = '#';
        btnCancel.innerHTML = '取消';
        btnCancel.style.display = editing?'inline-table':'none';
        btnCancel.style.width='45px';
        btnCancel.style.textAlign ="right";
        btnCancel.style.margin ="0 5px 0 5px";
        btnCancel.style.backgroundImage ='url('+Rsd.getRedjsHost() + "/resources/svg/cancel.svg"+')';
        btnCancel.style.backgroundPosition ='left center';
        btnCancel.style.backgroundSize = '12px';
        btnCancel.style.backgroundRepeat = 'no-repeat' ;
        $(btnCancel).click(function () {
 
            var tr = this.parentNode.parentNode.parentNode; 
            me.items[1].editTr(tr,false);
            //
            btnUpdate.style.display = 'inline-table';
            btnDel.style.display = 'inline-table';
            btnSave.style.display = 'none';
            btnCancel.style.display = 'none'; 
        }); 

        return [btnUpdate,btnSave,btnDel, btnCancel];
    },
     
    /*
     *
     * */
    loadMajor:function loadMajor(data)
    {
        var _major =  this.items[0];
        try {
            _major.loadData(data);
        } catch (ex) {
            Rsd.error('加载主表数据失败', 'Rsd.widget.MajorSubForm',ex);
        }
    },
    /*
     *
     * */
    loadSub:function loadSub(args,callback)
    {
        var _grid = this.items[1];
        try {
            _grid.loadData(args,callback);
        } catch (ex) {
            Rsd.error('加载从表数据失败', 'Rsd.widget.MajorSubForm',ex);
        }
 
    },
    /**
     * 
     * @param {*} editable 
     */
    setMajorMode:function setMajorMode(editable)
    {
        this.items[0].setMode(editable);
    },
    /**
     * 
     */
    modifyMajor:function modifyMajor(callback)
    {   
        if(callback)
        {
            callback();
        }
    },
    /**
     * @description 需要在引用的父类中，覆盖该方法
     */
    saveMajor:function saveMajor(callback)
    { 
        Rsd.popup('未实现');
        if(callback)
        {
            callback();
        } 
    },
    /**
     * 
     */
    cancelMajorModify:function(callback)
    { 
        if(callback)
        {
            callback();
        }
         
    },
    /**
     * @description 末尾行追加一条记录
     * @param {*} row 
     */
    addSub:function addSub(row,editable,index)
    {
        var _sub = this.items[1]; 
        _sub.newRow(row,editable,index);
    },
    /**
     * @description 获取数据
     */
    getData:function getData(target)
    { 
        if(target && target == 'major')
        {
            if(this.items[0].checkRecord()==false)
            {
                this.items[0].showError(); 
                return null;
            }
            return this.items[0].getRecord();
        }

        if(target && target == 'sub')
        {
            return this.items[1].dataSource||[];
        }

        var data = {major:null,sub:[]};
        if(this.items[0].checkRecord()==false)
        {
            this.items[0].showError();  
        }else
        {
            data.major = this.items[0].getRecord()
        }

        data.sub = this.items[1].getData() ||[];
        return data;
    },
    /**
     * 
     * @returns 获取从表行数，含表头
     */
    getSubRowCount:function getSubRowCount()
    {
        return this.items[1].getRowCount();
    },
    /**
     * @description 需要在引用的父类中，覆盖该方法
     */
    deleteSubItem:function deleteSubItem(row,evt,callback)
    {
        console.log(arguments);
        Rsd.popup('未实现');
    },
    /**
     * @description 需要在引用的父类中，覆盖该方法
     * @param {*} row 
     */
    saveSubItem:function saveSubItem(row,evt,callback)
    {
        console.log(arguments);
        Rsd.popup('未实现');
    }

},function (type) {

    var _subGetter = function () {

        return this.__sub||{modelType:'',fk:''};

    };

    var _subSetter = function (value) {
        
        if(Rsd.isObject(value.toolBar))
        { 
            if(Rsd.isObject(value.toolBar.header))
            {
                value.toolBar.header = Rsd.apply(this.items[1].toolBar.header||{},value.toolBar.header||{});
            }
            value.toolBar = Rsd.apply(this.items[1].toolBar||{},value.toolBar||{});
        }

        this.__sub = Rsd.apply({modelType:'',fk:''},value || {});
        
        this.items[1] = Rsd.apply(this.items[1],this.__sub);
        if(this.items[1].columns.length > 0)
        {
            Array.prototype.push.apply(this.items[1].columns, this.opColumns||[]);  
        }     
    }

    this.defineProperty(type,"sub", _subGetter, _subSetter,true);

    var _majorGetter = function () {

        return this.__major||{key:'',titleField:''} ;

    };

    var _majorSetter = function (value) {

        if(Rsd.isObject(value.header))
        { 
            value.header = Rsd.apply(this.items[0].header||{},value.header||{});
        }
         
        this.__major = Rsd.apply({key:'',titleField:''},value || {});
       
        this.items[0] = Rsd.apply(this.items[0],this.__major);
         
    }

    this.defineProperty(type,"major", _majorGetter, _majorSetter,true);

     

});
